// var config = require('../config/'); 
var then = require('thenjs');
var gm        = require('gm');
var webdriverio = require('webdriverio');
var client = {};
var urllib = require('urllib');
var options = {
    desiredCapabilities: {
        browserName: 'phantomjs'
    }
};
var fs        = require('fs');
var tesseract = require('node-tesseract');
var urlCache = {};
var config = require('../config');
var Actions = {
    init: function(){
        client = webdriverio
        .remote(options)
        .init()
        .windowHandleSize({width: 1200, height: 600})
        .url('http://tongji.baidu.com/web/welcome/login')
        .leftClick('.dazzle-button-text')
        Actions.fillIn();
        // clearInterval(Actions.startGetDataTimeOut);
    },
    fillIn: function(){
        console.info('填写用户名密码');
        client
        .setValue('#UserName', 'aiskater')
        .setValue('#Password', 'dangtuo2008')
        setTimeout(function(){
            console.info('验证码');
            Actions.getCASCode();
        },1000)
        // .getTitle().then(function(title) {
        //     console.info('验证码');
        // })
    },
    callback: function(err,code){
        console.info('code',code);
        if(code.length != 4){
            Actions.getCASCode();
        }else{
            Actions.login(code);
        }
    },
    over: function(){
        client.end();
    },
	/*
	 * 
	*/
	login : function (code) {
        client
        .setValue('#Valicode', code)
        .saveScreenshot('./2.png')
        .leftClick('.login-btn')
        .waitForExist('#ErrorTip',10000).then(function(isVisible) {
            client.saveScreenshot('./1.png');
            if(isVisible){
                Actions.fillIn();
                // return;
            }else{

            }
            clearTimeout(Actions.successTimeOut);
            console.log('login error',isVisible); // outputs: false
        })
        Actions.successTimeOut = setTimeout(function(){
            client.waitForExist('#MoreNav').then(function(isVisible) {
                console.log('login success'); // outputs: false
                client.getCookie().then(function(cookies) {
                    client.close();
                        Actions.startGetDataTimeOut = setInterval(function(){
                            Actions.startGetData(cookies);
                        },5000)
                });
            })
        },10000)
    },
    getCookieStr: function(cookies){
        var cookAry=[];
        for (var i = 0; i < cookies.length; i++) {
            var item = cookies[i];
            cookAry.push(item['name']+'='+item['value']);
        };
        return cookAry.join('; ');
    },
    startGetData: function(cookies){
        var url = 'http://tongji.baidu.com/web/7441284/ajax/post';
            var options = {
                method: 'POST',
                timeout: 10*1000,
                headers: {
                    'Cookie': Actions.getCookieStr(cookies),
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Referer': 'http://tongji.baidu.com/web/7441284/trend/latest?siteId=6790068',
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Connection': 'keep-alive',
                },
                data: {
                    indicators: 'area,start_time,source,access_page,ip,visitorId,visit_time,visit_pages',
                    method: 'trend/latest/a',
                    offset: 0,
                    order: 'start_time,desc',
                    queryId: '',
                    reportId: 4,
                    siteId: '6570934',
                    // 来源百度
                    // source: 'search,1',
                }
            }
            // console.info('options',options);
            // console.info('url',url);
            urllib.request(url, options, function(err, data, res){
                if (err) {
                    throw err; // you need to handle error 
                }
                // console.log(res.statusCode);
                // console.log(res.headers);
                // data is Buffer instance 
                var data = JSON.parse(data.toString())
                try{                
                    if(!data['data'])return;
                    var items = data['data']['items'];
                    if(!items)return;
                    items = items[0];
                }catch(e){
                    console.info('ERROR:',e);
                    items = [];
                }

                Actions.sendItems(items);
            });
    },
/*
{ fromType: '百度(搜索词:牛商网)',
  url: 'http://www.baidu.com/link?url=D5YKBoLiNDtOC0-j3OKfGI3eCEtQjSx0dFyBIObs4FS&wd=%E7%89%9B%E5%95%86%E7%BD%91&eqid=956fbfa6000063e10000000257433580' }
*/ 
    sendItems: function(items){
        for(var i =0;i<items.length;i++){
            try{
                var item = items[i];
                var fromType = item[0]['detail']['fromType'];
                fromType['fromType'] = fromType['fromType'].replace(/百度\(搜索词:|\)/g,'');
            }catch(e){
                continue;
            }
            if(urlCache[fromType['url']]){
                continue;
            }
            if(parseInt(Math.random()*10000) == 1000){
                urlCache = {};
            }
            urlCache[fromType['url']]=true;
            var options = {
                method: 'POST',
                timeout: 10*1000,
                data: fromType
            }
            console.info(options);
            urllib.request(config.trackingHost, options, function(err, data, res){
                console.info(data.toString());
            });
        }
    },
    getCASCode: function(code){
        client
        .leftClick('#change_cas')
        .saveScreenshot('./snapshot.png')
        // .timeoutsImplicitWait(1000)
        .getTitle().then(function(title) {
            // console.log('Title was: ' + title);
            gm('./snapshot.png')
            .crop(76,40, 620,332)
            .write('./snapshot1.png', function (err) {
                processImg('./snapshot1.png', './snapshot_temp.png')
                .then(recognizer)
                .then(text => {
                    Actions.callback(null,text);
                    // console.log(`识别结果:${text}`);
                })
                .catch((err)=> {
                    console.error(`识别失败:${err}`);
                });
            })
        })
    }
}

/**
 * 处理图片为阈值图片
 * @param imgPath
 * @param newPath
 * @param [thresholdVal=55] 默认阈值
 * @returns {Promise}
 */
function processImg (imgPath, newPath, thresholdVal) {
    return new Promise((resolve, reject) => {
        gm(imgPath)
            // .threshold(thresholdVal || 55)
            .write(newPath, (err)=> {
                if (err) return reject(err);

                resolve(newPath);
            });
    });
}

/**
 * 识别图片
 * @param imgPath
 * @param options tesseract options
 * @returns {Promise}
 */
function recognizer (imgPath, options) {
    // console.info('options',options);
    options = Object.assign({psm: 7}, options);

    return new Promise((resolve, reject) => {
        tesseract
            .process(imgPath, options, (err, text) => {
                if (err) return reject(err);
                resolve(text.replace(/[\r\n\s]/gm, ''));
            });
    });
}
module.exports = Actions;